<template>
  <view class="container">
    <view class="form-container">
      <view class="form-title">社区事件上报系统</view>
      <u--form labelPosition="left" :model="model" :rules="rules" ref="uForm">
        <u-form-item
            label="姓名"
            prop="userInfo.name"
            ref="item1"
            labelWidth="140rpx"
            border-bottom
            class="form-item"
        >
          <u--input
              v-model="model.userInfo.name"
              placeholder="请输入账户"
              border="none"
              class="form-input"
          ></u--input>
        </u-form-item>
        <u-form-item
            label="密码"
            prop="userInfo.password"
            ref="item2"
            labelWidth="140rpx"
            border-bottom
            class="form-item"
        >
          <u--input
              v-model="model.userInfo.password"
              placeholder="请输入密码"
              type="password"
              border="none"
              class="form-input"
          ></u--input>
        </u-form-item>
        <u-form-item
            label="验证码"
            prop="userInfo.code"
            ref="item3"
            labelWidth="140rpx"
            border-bottom
            class="form-item"
        >
          <u--input
              v-model="model.userInfo.code"
              placeholder="请输入验证码"
              border="none"
              class="form-input"
          ></u--input>
          <u--image :src="src" :width="100" :height="38" @click="getUrlCodeImg" class="captcha"></u--image>
        </u-form-item>
        <view style="text-align: center; margin-top: 60rpx;">
          <u-button @click="submit" type="primary" class="login-button">登录</u-button>
        </view>
      </u--form>
    </view>
  </view>
</template>

<script>
import { login,getDict,getUserInfo,getCaptchaImage } from '@/api/exam/login'
import {getToken, setToken} from "../../util/auth";
import "util/mobile-detect.min.js";
import {generateRandomString} from "../../util/common";

export default {
  data() {
    return {
      src: '',
      model: {
        userInfo: {
          name: localStorage.getItem('name'),
          password: localStorage.getItem('password'),
        },
      },
      checkBox:[],
      rules: {
        'userInfo.name': {
          type: 'string',
          required: true,
          message: '请填写账户',
          trigger: ['blur', 'change']
        },
        'userInfo.password': {
          type: 'string',
          required: true,
          message: '请填写密码',
          trigger: ['blur', 'change']
        },
        'userInfo.code': {
          type: 'string',
          required: true,
          message: '请填写验证码',
          trigger: ['blur', 'change']
        },
      },
    }
  },
  methods: {
    getUrlCodeImg(){
      getCaptchaImage().then(res=>{
        if (res.img) this.src = "data:image/gif;base64," + res.img
        this.model.userInfo.uuid = res.uuid;
      }).catch(err=>{})
    },

    /**
     * 获取url中code参数
     * @return {Object}
     */
    getUrlCode() {
      // 截取url中的code方法
      const url = location.search;
      const theRequest = new Object();
      if (url.indexOf("?") !== -1) {
        const str = url.substr(1);
        const strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
        }
      }
      console.log(theRequest);
      return theRequest
    },
    /**
     * 获取微信code
     */
    getCode() {
      const code = this.getUrlCode().code;// 截取code
      this.code = code;
      if (this.code) {
        if (!localStorage.getItem('openid')){
          getUserInfo(this.code).then(res=>{
            if (res.openid) localStorage.setItem('openid',res.openid)
          }).catch(err=>{})
        }
      }else{
        if (!localStorage.getItem('openid')){
          uni.$u.toast('请在微信端登录')
          uni.redirectTo({
            url:"/pages/exam/error/error?text=请在微信端登录"
          })
        }
      }
    },

    checkboxChange(e){

    },
    sexSelect(e) {
      this.model.userInfo.sex = e.name
      this.$refs.uForm.validateField('userInfo.sex')
    },
    // 打开或创建数据库
    async openDB() {
      return new Promise((resolve, reject) => {
        const request = window.indexedDB.open('myDB', 1);
        request.onerror = (event) => {
          reject('Failed to open database');
        };

        request.onupgradeneeded = (event) => {
          const db = event.target.result;

          // 创建一个名为 'data' 的对象存储空间
          db.createObjectStore('data', { keyPath: 'id' });
        };

        request.onsuccess = (event) => {
          const db = event.target.result;
          resolve(db);
        };
      });
    },

    // 存储数据到数据库
    async saveData(data) {
      const db = await this.openDB()
      return new Promise((resolve, reject) => {
        const transaction = db.transaction(['data'], 'readwrite');
        const objectStore = transaction.objectStore('data');

        const request = objectStore.add(data);

        request.onsuccess = (event) => {
          resolve('Data saved successfully');
        };

        request.onerror = (event) => {
          reject('Failed to save data');
        };
      });
    },

    // 从数据库获取数据
    async getData(id) {
      const db = await this.openDB()
      return new Promise((resolve, reject) => {
        const transaction = db.transaction(['data'], 'readonly');
        const objectStore = transaction.objectStore('data');

        const request = objectStore.get(id);

        request.onsuccess = (event) => {
          const data = event.target.result;
          resolve(data);
        };

        request.onerror = (event) => {
          reject('Failed to get data');
        };
      });
    },

    async generateDeviceId() {
      let deviceId = ''
      await this.getData(1).then(async (data) => {
        if (!data){
          let temp = generateRandomString(32)
          await this.saveData({id: 1, deviceId: temp })
          deviceId = temp
        }else{
          deviceId = data.deviceId;
        }
      })
      return deviceId
    },


    generateDeviceIdLocal() {
      const deviceInfo = wx.getSystemInfoSync();
      const deviceId = deviceInfo.deviceId;
      console.log('设备ID:', deviceId);
      return deviceId;
    },

    submit(){
      if (!localStorage.getItem('openid')){
        uni.redirectTo({
          url:"/pages/exam/error/error?text=请用微信重新授权"
        })
        return uni.$u.toast('请用微信重新授权')
      }
      this.$refs.uForm.validate().then(async res => {
        // uni.$u.toast('校验通过')
        let params = {
          username: this.model.userInfo.name,
          password: this.model.userInfo.password,
          uuid: this.model.userInfo.uuid,
          code : this.model.userInfo.code,
        }
        uni.showLoading({
          title: '正在登录'
        })
        login(params).then(async response => {
          // 处理登录响应
          if (response.code===200){
            setToken(response.token)

            // 记住密码
            if (this.checkBox.toString()==='remember'){
               localStorage.setItem('name',this.model.userInfo.name)
               localStorage.setItem('password',this.model.userInfo.password)
            }else{
              localStorage.removeItem('name')
              localStorage.removeItem('password')
            }

            localStorage.setItem('userName',this.model.userInfo.name)
            localStorage.setItem('userId',response.userId)

            // 获取配置文件
            this.getConfigs()
            if (!localStorage.getItem("exam_topic_type")){
              await getDict("exam_topic_type").then(res => {
                localStorage.setItem("exam_topic_type",JSON.stringify(res.data))
              });
            }
            if (!localStorage.getItem("exam_type")){
              await getDict("exam_type").then(res => {
                localStorage.setItem("exam_type",JSON.stringify(res.data))
              });
            }


            uni.redirectTo({
              url:"/pages/exam/content"
            })
          }
        }).catch(err => {
          this.getUrlCodeImg()
          // 处理登录错误
        }).finally(res=>{
          uni.hideLoading()
        })
      }).catch(errors => {

        // uni.$u.toast('校验失败')
      })
    },
    getConfigs(){
      // getDict('exam_system_config').then(res => {
      //   let finalResult = {}
      //   res.data.map(item=>{
      //     finalResult[item.dictLabel] = item.dictValue
      //   });
      //   localStorage.setItem('exam_system_config',JSON.stringify(finalResult))
      // });
    }
  },
  onReady() {
    let localId = this.generateDeviceIdLocal()
    localStorage.setItem('openid',localId)
    
    this.getCode()
    this.getUrlCodeImg()
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules)
    if (getToken()){
      uni.redirectTo({url:'/pages/exam/content'})
    }
  },
}
</script>

<style>
body {
  background: url('https://images.unsplash.com/photo-1604014237554-927b4343a2b6?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80') no-repeat center center fixed;
  background-size: cover;
  background-position: center;
}
.container {
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
}

.form-container {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 20rpx;
  padding: 40rpx;
  margin-top: 40%;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 600rpx;
}

.form-title {
  text-align: center;
  margin-bottom: 40rpx;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-input {
  padding: 20rpx 0;
  font-size: 28rpx;
}

.captcha {
  margin-left: 20rpx;
  cursor: pointer;
}

.login-button {
  width: 100%;
  font-size: 32rpx;
  padding: 20rpx 0;
  background-color: #1E90FF;
  border: none;
  border-radius: 10rpx;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  color: #fff;
}
</style>
